//
//  YZMRegAuthViewController.m
//  YZMicroStock
//
//  Created by Lv.Dongdong on 16/3/28.
//  Copyright © 2016年 cqjr. All rights reserved.
//

#import "YZMRegAuthViewController.h"
#import "YZMHintInputView.h"
#import "YZMAuthCodeView.h"
#import "YZClient+Account.h"
#import "YZGeneralResultModel.h"
#import "YZMWebViewService.h"
#import "Zhugeio/Zhuge.h"
#import "YZMLoginViewController.h"

@interface YZMRegAuthViewController () <UITextFieldDelegate>

@property (nonatomic, strong) UIScrollView *scrollView;
@property (nonatomic, strong) NSString *phoneString;
@property (nonatomic, strong) NSString *codeString;
@property (nonatomic, strong) YZMHintInputView *nicknameView;
@property (nonatomic, strong) YZMHintInputView *passwordView;
@property (nonatomic, strong) YZMHintInputView *truePasswordView;
@property (nonatomic, copy) NSString *nextPageName;
@property (nonatomic, strong) NSDictionary *nextPageParams;
@property (nonatomic, copy) NSString *srcPageName;

@property (nonatomic, assign) BOOL dismissFlag;
@property (nonatomic, strong) void (^srcAction)();
@property (nonatomic, strong) void (^backAction)();


@end

@implementation YZMRegAuthViewController {
    UIButton *_registerButton;
}

- (void)dealloc {
    
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:YES];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(showKeyboard:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(hideKeyboard:) name:UIKeyboardWillHideNotification object:nil];
}

- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:YES];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
}


#pragma mark -- KeyboardNotification
- (void)showKeyboard:(NSNotification *)noti {
    NSDictionary *dic = noti.userInfo;
    //键盘弹出后的位置
    CGRect endFrame = [dic[UIKeyboardFrameEndUserInfoKey] CGRectValue];
    [self.scrollView mas_updateConstraints:^(MASConstraintMaker *make){
        make.bottom.equalTo(self.view).offset(-endFrame.size.height);
    }];
}

- (void)hideKeyboard:(NSNotification *)noti {
    
    [self.scrollView mas_updateConstraints:^(MASConstraintMaker *make){
        make.bottom.equalTo(self.view);
    }];
}

#pragma mark -- init
- (id)init {
    if (self = [super init]) {
        self.view.backgroundColor = [YZMAppStyle appBackgroundColor];
        self.title = @"注册";
    }
    return self;
}

+ (instancetype)createWithParams: (NSDictionary *)params
{
    YZMRegAuthViewController *ctrl = [[self alloc] init];
    ctrl.nextPageName = params[YZNEXTPAGE];
    ctrl.nextPageParams = params[YZNEXTPAGEPARAMS];
    ctrl.srcPageName  = params[YZSOURCEPAGE];
    ctrl.phoneString = [params objectForKey:@"mobile"];
    ctrl.codeString = [params objectForKey:@"code"];
    ctrl.dismissFlag = [params[YZDismissFlag] boolValue];
    ctrl.srcAction = params[YZSOURCEACTION];
    ctrl.backAction = params[YZBACKACTION];
    
    return ctrl;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self createObjects];
}

#pragma mark -- createObjects
- (void)createObjects {
    WS(ws)
    
    self.scrollView = [[UIScrollView alloc] init];
    CGSize contentSize = CGSizeMake(self.view.bounds.size.width, self.view.bounds.size.height - 64);
    if (iPhone4 || iPhone5) {
        self.scrollView.showsHorizontalScrollIndicator = NO;
        self.scrollView.showsVerticalScrollIndicator = NO;
        self.scrollView.contentSize = contentSize;
        self.scrollView.bounces = NO;
    }
    [self.view addSubview:self.scrollView];
    
    self.nicknameView = [[YZMHintInputView alloc] init];
    [self.scrollView addSubview:self.nicknameView];
    self.nicknameView.inputLabel.text = @"用户名";
    self.nicknameView.textField.placeholder = @"请设置您的用户名";
    self.nicknameView.textField.keyboardType = UIKeyboardTypeDefault;
    self.nicknameView.textField.returnKeyType = UIReturnKeyDone;
    self.nicknameView.textField.delegate = self;
    [self.nicknameView.textField addTarget:self action:@selector(textFieldchange:) forControlEvents:UIControlEventEditingChanged];
    
    self.nicknameView.lineTopView.hidden=NO;
    self.nicknameView.lineBottomView.hidden=NO;
    
    self.passwordView = [[YZMHintInputView alloc] init];
    [self.scrollView addSubview:self.passwordView];
    self.passwordView.inputLabel.text = @"登录密码";
    self.passwordView.textField.placeholder = @"6-16位数字和字母组成";
    self.passwordView.textField.keyboardType = UIKeyboardTypeDefault;
    self.passwordView.textField.returnKeyType = UIReturnKeyNext;
    self.passwordView.textField.secureTextEntry = YES;
    self.passwordView.lineTopView.hidden=NO;
    self.passwordView.lineBottomView.hidden=NO;
    self.passwordView.textField.delegate = self;
    [self.passwordView.textField addTarget:self action:@selector(textFieldchange:) forControlEvents:UIControlEventEditingChanged];
    
    self.truePasswordView = [[YZMHintInputView alloc] init];
    [self.scrollView addSubview:self.truePasswordView];
    self.truePasswordView.inputLabel.text = @"确认密码";
    self.truePasswordView.textField.placeholder = @"请输入确认密码";
    self.truePasswordView.textField.keyboardType = UIKeyboardTypeDefault;
    self.truePasswordView.textField.returnKeyType = UIReturnKeyNext;
    self.truePasswordView.textField.delegate = self;
    [self.truePasswordView.textField addTarget:self action:@selector(textFieldchange:) forControlEvents:UIControlEventEditingChanged];
    
    self.truePasswordView.lineTopView.hidden=NO;
    self.truePasswordView.lineBottomView.hidden=NO;
    
    UIButton *showPwdButton = [UIButton buttonWithType: UIButtonTypeCustom];
    [showPwdButton setImage: [UIImage imageNamed: @"pwd_hide"] forState: UIControlStateNormal];
    [showPwdButton addTarget:self action:@selector(showBtnUpAction:) forControlEvents:UIControlEventTouchUpInside];
    
    
    
    _registerButton = [YZMAppStyle NewsubmitButton];
    [_registerButton setTitle:@"注册" forState:UIControlStateNormal];
    [_registerButton addTarget:self action:@selector(registerStep) forControlEvents:UIControlEventTouchUpInside];
    _registerButton.enabled = NO;
    [self.scrollView addSubview:_registerButton];
    
    UILabel *protocolLabel = [YZMAppStyle labelWithSmallLightGray];
    protocolLabel.text = @"点击注册即同意";
    [self.scrollView addSubview:protocolLabel];
    
    UIButton *protocolButton = [UIButton buttonWithType:UIButtonTypeSystem];
    [protocolButton setTitle:@"《微策略服务协议》" forState:UIControlStateNormal];
    [protocolButton setTitleColor:[YZMAppStyle colorForBlueText] forState:UIControlStateNormal];
    [protocolButton.titleLabel setFont:[YZMAppStyle smallSizeFont]];
    [protocolButton addTarget:self action:@selector(UserProtocolAgree) forControlEvents:UIControlEventTouchUpInside];
    [self.scrollView addSubview:protocolButton];
    
    //createConstraint
    [self.scrollView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(ws.view);
    }];
    
//    [self.authCodeView mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.top.width.left.equalTo(ws.scrollView);
//        make.height.mas_equalTo(62);
//    }];
    
    [self.nicknameView mas_makeConstraints:^(MASConstraintMaker *make) {
        //        make.top.equalTo(ws.passwordView.mas_bottom).with.offset(ControlSpacing15);
        //        make.width.height.equalTo(ws.passwordView);
        //        make.left.right.equalTo(ws.view);
        make.top.equalTo(ws.scrollView).with.offset(10);
        make.width.left.equalTo(ws.scrollView);
        make.height.mas_equalTo(InputViewHeight);
    }];
    
    [self.passwordView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(ws.view);
        make.top.equalTo(ws.nicknameView.mas_bottom).with.offset(10);
        make.height.mas_equalTo(InputViewHeight);
    }];
    
    [self.passwordView appendRightWidget:showPwdButton isShowSegmentLine:NO];
    
    [self.truePasswordView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(ws.view);
        make.top.equalTo(ws.passwordView.mas_bottom).with.offset(10);
        make.height.mas_equalTo(InputViewHeight);
    }];
    
    [_registerButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(ws.view).with.offset(ControlSpacing20);
        make.right.equalTo(ws.view).with.offset(-ControlSpacing20);
        make.top.equalTo(ws.truePasswordView.mas_bottom).with.offset(ControlSpacing30);
    }];
    
    [protocolLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_registerButton.mas_bottom).with.offset(ControlSpacing15);
        make.right.equalTo(ws.view.mas_centerX).with.offset(-ControlSpacing10);
        make.height.mas_equalTo(ControlHeight15);
    }];
    
    [protocolButton mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(protocolLabel.mas_right);
        make.centerY.equalTo(protocolLabel);
    }];
}

#pragma mark -- buttonEvents
- (void)showBtnUpAction:(UIButton *)send {
    if (self.passwordView.textField.isSecureTextEntry) {
        self.passwordView.textField.secureTextEntry = NO;
        [send setImage: [UIImage imageNamed: @"pwd_show"] forState: UIControlStateNormal];
    } else {
        self.passwordView.textField.secureTextEntry = YES;
        [send setImage: [UIImage imageNamed: @"pwd_hide"] forState: UIControlStateNormal];
    }
}

- (void)UserProtocolAgree {
    [self resignAllFirstResponder];
    [YZMWebViewService openRegisterAgreement];
}

- (void)registerStep {
    
    [self resignAllFirstResponder];
    
    if (![self checkInputContent:self.nicknameView.textField] || ![self checkInputContent:self.passwordView.textField] || ![self checkInputContent:self.truePasswordView.textField]) {
        return;
    }
    
    NSString *mobile = self.phoneString;
    NSString *smsCode = self.codeString;
    NSString *userName = self.nicknameView.textField.text;
    NSString *password = self.passwordView.textField.text;
    [YZClient registerWithMobile: mobile smsCode: smsCode username: userName password: password success:^(NSURLSessionDataTask *task,id responseObject) {
        YZGeneralResultModel *topModel = responseObject;
        if (topModel.success) {
            [MBProgressHUD showMessage: @"注册成功"];
#ifndef DEBUG_MODE
            
            [[Zhuge sharedInstance] track:@"注册-完成注册" properties:nil];
#endif
    
            [YZMUserServiceInstance loginWithUsername: userName password:password success:^(YZMLoginResultModel *result){
                if (result.authenticated) {
                    [MBProgressHUD showMessage: @"登录成功"];
                    [self loginSuccessAcction];
                }
                else
                {
                    [result showMessage];
                }
            } failure:^(NSError *error) {
                [error yz_showMessage];
            }];
        }
        else
        {
            [topModel showMessage];
        }
    } failure:^(NSError *error) {
        
        [error yz_showMessage];
    }];
    
}

- (void)loginSuccessAcction
{

    if (self.dismissFlag) {
        
        [YZMCMInstance dismissViewController];
        return;
    }
    
    if (self.nextPageName) {
        if (self.srcPageName) {
            [YZMCMInstance pushAfterName: self.srcPageName withControllerName: self.nextPageName andParams: nil];
        }
        else
        {
            if ([self.nextPageName isEqualToString:@"accountDetail"]) {
                [YZMCMInstance popToRootViewController];
                return;
            }
            [YZMCMInstance pushBeforeName: @"login" withControllerName: self.nextPageName andParams: self.nextPageParams];
        }
    }
    else if (self.srcPageName)
    {
        [YZMCMInstance popViewControllerToControllerName: self.srcPageName animated: YES];
        if (self.srcAction) {
            
            self.srcAction();
        }
    }
    else
    {
        [YZMCMInstance popToRootViewController];
    }
}

- (BOOL)checkInputContent:(UITextField *)textField {
    
    if (textField == self.nicknameView.textField) {
        
        if ([self userNameCount:self.nicknameView.textField.text] < 4 ||
            [self userNameCount:self.nicknameView.textField.text] > 16) {
            [self registerValidateFail:@"用户名为4-16个字符，中文算2个字符"];
            return NO;
        }
        
        if ([self.nicknameView.textField.text yz_isValidUserName]) {
            return YES;
        } else {
            [self registerValidateFail:@"用户名只允许字母、数字、下划线或中文"];
            return NO;
        }
    }
    
    if (textField == self.passwordView.textField) {
        
        if ([self.passwordView.textField.text yz_isValidPassword]) {
            return YES;
        } else {
            [self registerValidateFail:@"密码由6-16位数字和字母组成"];
            return NO;
        }
    }

    if (textField == self.truePasswordView.textField) {
        if (![self.truePasswordView.textField.text isEqualToString:self.passwordView.textField.text]) {
            [self registerValidateFail:@"确认密码与登录密码不一致！"];
            return NO;
        }else{
            return YES;
        }
    }

    return NO;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event {
    [self.view endEditing:YES];
}

- (void)resignAllFirstResponder {
    [self.passwordView.textField resignFirstResponder];
    [self.truePasswordView.textField resignFirstResponder];
    [self.nicknameView.textField resignFirstResponder];
}

#pragma mark -- UITextFieldDelegate
//点击键盘return
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    
    if (textField == self.passwordView.textField) {
        [self.nicknameView.textField becomeFirstResponder];
    } else if (textField == self.nicknameView.textField) {
        [self.nicknameView.textField resignFirstResponder];
    }
    
    return YES;
}

- (void)textFieldchange:(UITextField *)send {
    
    if ([self.passwordView.textField.text length] > 0 && [self.truePasswordView.textField.text length] > 0 && [self userNameCount:self.nicknameView.textField.text] > 0) {
        _registerButton.enabled = YES;
        _registerButton.layer.borderWidth=0.0;
        return;
    }
    _registerButton.layer.borderWidth=1.0;
    _registerButton.enabled = NO;
}

#pragma mark -- byteLength

- (NSUInteger)userNameCount:(NSString *)text {
    NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding(kCFStringEncodingGB_18030_2000);
    NSData* data = [text dataUsingEncoding:enc];
    return [data length];
}

#pragma mark -- registerValid

- (void)registerValidateFail:(NSString *)message {
    
    if (message) {
        [MBProgressHUD showMessage:message];
    }
}

@end
